package webEquipeRechercheGwt.client.allEntityShowingPanel;

import java.util.ArrayList;
import java.util.Collection;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;

import webEquipeRechercheGwt.client.callback.consultation.CallBackGetAllPaper;
import webEquipeRechercheGwt.client.callback.consultation.commands.CommandGetAllPapersImplAllPaperPanel;
import webEquipeRechercheGwt.client.entityMirror.PaperMirror;
import webEquipeRechercheGwt.client.handler.navigation.ClickHandlerGetPaperCreationLabel;
import webEquipeRechercheGwt.client.handler.navigation.ClickHandlerPaper;
import webEquipeRechercheGwt.client.services.PaperService;
import webEquipeRechercheGwt.client.services.PaperServiceAsync;
import webEquipeRechercheGwt.client.structure.DataShowingPanel;

public class AllPaperPanel extends AllEntityShowingPanel {

	private DataShowingPanel mainPanel;
	private Collection<PaperMirror> papers;
	
	public AllPaperPanel(DataShowingPanel mainPanel){
		this.mainPanel = mainPanel;
		papers = new ArrayList<PaperMirror>();
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		updateLabels();
		loadPapersFromServer();
	}
	
	private void loadPapersFromServer(){
		PaperServiceAsync service = GWT.create(PaperService.class);
		AsyncCallback<Collection<PaperMirror>> callback = new CallBackGetAllPaper(new CommandGetAllPapersImplAllPaperPanel(this));
		service.getPapers(callback);
	}

	public void setPapers(Collection<PaperMirror> papers) {
		this.papers = papers;
		updateLabels();
	}
	
	private void addCreationLink(){
		Button b = new Button("create new Paper");
		ClickHandler handler = new ClickHandlerGetPaperCreationLabel(mainPanel);
		b.addClickHandler(handler);
		add(b);
	}
	
	private void updateLabels(){
		clear();
		Label title = new Label("List of all papers");
		add(title);
		for(PaperMirror p : papers){
			Label l = new Label(p.getTitle());
			ClickHandler clickHandler = new ClickHandlerPaper(p, mainPanel);
			l.addClickHandler(clickHandler);
			add(l);
		}
		addCreationLink();
	}
}
